import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import {baseUrl} from "@/settings";


function closePage() {
    if (navigator.userAgent.indexOf("Firefox") != -1 || navigator.userAgent.indexOf("Chrome") != -1) {
        window.location.href = "about:blank";
        window.close();
    } else {
        window.opener = null;
        window.open("", "_self");
        window.close();
    }
}




// create an axios instance
const service = axios.create({
    // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
    baseURL: baseUrl+'/admin', // url = base url + request url
    // withCredentials: true, // send cookies when cross-domain requests
    timeout: 10000 // request timeout
})

// 请求拦截
service.interceptors.request.use(
    config => {
        // do something before request is sent
        let params = (config.params !== undefined ? config.params : config.data)
            // console.log('请求拦截', config)
        params['key'] = getToken()
            // console.log('请求拦截', params)
        params.api_path = config.url
            // 重新赋值
        if (config.params !== undefined) {
            config.params = params
        } else {
            config.data = params
        }
        if (store.getters.token) {
            // let each request carry token
            // ['X-Token'] is a custom headers key
            // please modify it according to the actual situation
            // config.headers['X-Token'] = getToken()
        }
        return config
    },
    error => {
        // do something with request error
        console.log(error) // for debug
        return Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    response => {
        // console.log('拦截器', response)
        const res = response.data
        if (res.code !== 200) { // 自定义返回
            console.log('致命错误', response)
            switch (res.code) {
                case 999:
                    MessageBox.confirm('登录过期，您可以关闭当前页面，或重新登录', '确认注销', {
                        confirmButtonText: '重新登录',
                        cancelButtonText: '关闭当前页面',
                        type: 'warning'
                    }).then(() => {
                        store.dispatch('user/resetToken').then(() => {
                            location.reload()
                        })
                    }).catch(() => {
                        console.log('关闭页面')
                        closePage()
                    })
                    break
                case 400:
                    Message.error(res.datas.error);
                    break
                default:
                    Message.error('未知错误，请联系超级管理员');
            }
            return Promise.reject(res)
        } else {
            return res.datas
        }
    },
    error => {
        console.log('致命错误2', error)
        if (error && error.response) {
            switch (error.response.status) {
                case 400:
                    error.message = '错误请求'
                    break
                case 401:
                    error.message = '未授权，请重新登录'
                    break
                case 403:
                    error.message = '拒绝访问'
                    break
                case 404:
                    error.message = '请求错误,未找到该资源'
                    break
                case 405:
                    error.message = '请求方法未允许'
                    break
                case 408:
                    error.message = '请求超时'
                    break
                case 500:
                    error.message = '服务器端出错'
                    break
                case 501:
                    error.message = '网络未实现'
                    break
                case 502:
                    error.message = '网络错误'
                    break
                case 503:
                    error.message = '服务不可用'
                    break
                case 504:
                    error.message = '网络超时'
                    break
                case 505:
                    error.message = 'http版本不支持该请求'
                    break
                default:
                    error.message = `未知错误${error.response.status}`
            }
        } else {
            error.message = '服务器繁忙,请稍后重试'
        }
        Message({
            message: error.message,
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error)
    }
)

export default service
